#!/usr/bin/env python3
import click
import os
from pathlib import Path

@click.group(help='Ubuntu下service文件维护工具')
def cli():
    pass

TPL="""\
[Unit]
Description={title}

[Service]
User=root
Group=root
Type=simple
Restart=always
RestartSec=20
StartLimitInterval=0
Nice=10
WorkingDirectory={workdir}
ExecStart={cmd}
StandardOutput=null
TimeoutStartSec=30

[Install]
RequiredBy=multi-user.target
"""

def gen(title: str, workdir:str, cmd:str):
    ret = TPL.format(**{
        "title": title,
        "workdir": str(Path(workdir).absolute()),
        "cmd": cmd
    })
    print(ret)
    return ret

@cli.command(help='测试service文件，sudo cp xxx.service /lib/systemd/system/')
@click.option('--workdir', '-w', default='.', help='工作目录')
@click.option('--output', '-o', default='', help='输出文件')
@click.argument('name')
@click.argument('cmd')
def test(workdir:str, output:str, name: str, cmd:str):
    ret = gen(name+' Service', workdir, cmd)
    if output:
        with open(output, 'w') as f:
            f.write(ret)

@cli.command(help='生成service文件，并自动启动')
@click.option('--workdir', '-w', default='.', help='工作目录')
@click.option('--enable', type=bool, default=True, help='自动使能')
@click.option('--start', type=bool, default=True, help='自动启动')
@click.argument('name')
@click.argument('cmd')
def new(workdir:str, enable:bool, start: bool, name: str, cmd:str):
    ret = gen(name+' Service', workdir, cmd)
    fn = f"/tmp/{name}.service"
    with open(fn, 'w') as f:
        f.write(ret)
    os.system(f'sudo cp {fn} /lib/systemd/system/')
    os.system('sudo systemctl daemon-reload')
    if enable:
        os.system(f'sudo systemctl enable {name}')
    if start:
        os.system(f'sudo systemctl start {name}') 

if __name__ == '__main__':
    cli()
